package cn.wellsun;
import cn.wellsun.util.RandomUtil;
import cn.wellsun.util.utildm2.Question;
import org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
 * 主程序
 * @author zchcpy
 */
public class Main implements ActionListener {
	private JFrame frame;
	private JButton btnReset;
	String emptyStr = "";
	private String logoPath = "";
	private File logoPathChoose = null;
	private JButton btnAna;
	private JButton btnAnb;
	private JButton btnAnc;
	private JButton btnAnd;
	private JRadioButton rmiBtnE;
	private JRadioButton rmiBtnM;
	private JRadioButton rmiBtnH;
	private int initQuestionItem = 0;
	/**
	 * 每题的基础分数 根据难度变化
	 */
	private int pointPerQues = 1;
	private int getPoint = 0;
	private JLabel lblQuestion;
	private Map<Object, Object> answerCount = new HashMap<>();
	private final String currentRootPath = Objects.requireNonNull(Thread.currentThread().getContextClassLoader().getResource(emptyStr)).getPath();
	/**
	 * 问题List
	 */
	private ArrayList<Question> questions;
	private JLabel lblScore;
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			@Override
			public void run() {
				try {
					BeautyEyeLNFHelper.frameBorderStyle = BeautyEyeLNFHelper.FrameBorderStyle.translucencyAppleLike;
					org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper.launchBeautyEyeLNF();
					// 设置此开关量为false即表⽰示关闭之，BeautyEye LNF中默认是true
					BeautyEyeLNFHelper.translucencyAtFrameInactive = true;
					UIManager.put("RootPane.setupButtonVisible", false);
					BeautyEyeLNFHelper.commonBackgroundColor.darker();
					Main window = new Main();
					window.frame.setVisible(true);
				}
				catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	private Main() {
		initialize();
		String quesPath = (currentRootPath + "questions/Questions.txt");
		questions = Question.readQuestions(quesPath);
		checkQuesDegree();
		setAnswersBtn(0);
	}
	private void initialize() {
		frame = new JFrame();
		frame.setTitle("multiple choice questions");
		String iconPath = "icon/icon-app.png";
		String appIcon = (currentRootPath + iconPath).substring(1);
		String lblQuesPath = "img/qSmall.png";
		String lblQuestionIcon = (currentRootPath + lblQuesPath).substring(1);
		File fileAppIcon = new File(appIcon);
		BufferedImage bi = null;
		try {
			bi = ImageIO.read(fileAppIcon);
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		frame.setIconImage(bi);
		frame.setBounds(100, 100, 659, 502);
		frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		frame.setResizable(false);
		frame.setLocationRelativeTo(null);
		frame.getContentPane().setLayout(null);
		JPanel panel = new JPanel();
		panel.setBounds(0, 0, 643, 464);
		frame.getContentPane().add(panel);
		panel.setLayout(null);
		// 重置按钮
		btnReset = new JButton("Reset");
		btnReset.addActionListener(this);
		btnReset.setBounds(310, 374, 110, 37);
		panel.add(btnReset);
		JButton btnOpenExplore = new JButton("打开");
		btnOpenExplore.addActionListener(this);
		btnOpenExplore.setBounds(252, 125, 65, 25);
		lblQuestion = new JLabel("Question 1: What is the capital of France?");
		lblQuestion.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		lblQuestion.setBounds(10, 25, 623, 31);
		lblQuestion.setIcon(new ImageIcon(lblQuestionIcon));
		panel.add(lblQuestion);
		JMenuBar menuBar = new JMenuBar();
		menuBar.setBounds(0, 0, 643, 21);
		panel.add(menuBar);
		JMenu menu = new JMenu("难度");
		menuBar.add(menu);
		ButtonGroup buttonGroup = new ButtonGroup();
		rmiBtnE = new JRadioButton("简单");
		rmiBtnE.setSelected(true);
		rmiBtnE.addActionListener(this);
		menu.add(rmiBtnE);
		rmiBtnM = new JRadioButton("中等");
		rmiBtnM.addActionListener(this);
		menu.add(rmiBtnM);
		rmiBtnH = new JRadioButton("困难");
		rmiBtnH.addActionListener(this);
		menu.add(rmiBtnH);
		buttonGroup.add(rmiBtnE);
		buttonGroup.add(rmiBtnM);
		buttonGroup.add(rmiBtnH);
		JLabel label = new JLabel("分数：");
		label.setBounds(162, 374, 36, 37);
		panel.add(label);
		JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		tabbedPane.setBorder(new LineBorder(new Color(240, 248, 255), 5, true));
		tabbedPane.setBounds(20, 57, 576, 307);
		panel.add(tabbedPane);
		JPanel panelAnswers = new JPanel();
		panelAnswers.setBorder(null);
		panelAnswers.setBounds(0, 0, 300, 464);
		tabbedPane.addTab("Click the button to pick an answer here:", null, panelAnswers, null);
		panelAnswers.setLayout(null);
		btnAna = new JButton();
		btnAna.setBounds(24, 28, 510, 37);
		btnAna.addActionListener(this);
		panelAnswers.add(btnAna);
		btnAnb = new JButton();
		btnAnb.setBounds(24, 95, 510, 37);
		btnAnb.addActionListener(this);
		panelAnswers.add(btnAnb);
		btnAnc = new JButton();
		btnAnc.setBounds(24, 153, 510, 37);
		btnAnc.addActionListener(this);
		panelAnswers.add(btnAnc);
		btnAnd = new JButton();
		btnAnd.setBounds(24, 215, 510, 37);
		btnAnd.addActionListener(this);
		panelAnswers.add(btnAnd);
		lblScore = new JLabel("0");
		lblScore.setHorizontalAlignment(SwingConstants.CENTER);
		lblScore.setFont(new Font("微软雅黑", Font.BOLD | Font.ITALIC, 13));
		lblScore.setForeground(new Color(70, 130, 180));
		lblScore.setBounds(230, 377, 54, 31);
		panel.add(lblScore);
	}
	/**
	 * 事件监听 逻辑枢纽
	 */
	@Override
	public void actionPerformed(ActionEvent e) {
		Object s = e.getSource();
		// 注意了，这里重要的一句 选择文件夹
		if (s == btnReset) {
			initQuestionItem = 0;
			setAnswersBtn(0);
			lblScore.setText("0");
		}
		// 答案选择
		else if (s == btnAna) {
			checkAnswer(btnAna);
		}
		else if (s == btnAnb) {
			checkAnswer(btnAnb);
		}
		else if (s == btnAnc) {
			checkAnswer(btnAnc);
		}
		else if (s == btnAnd) {
			checkAnswer(btnAnd);
		}
		// 难度选择
		else if (s == rmiBtnE || s == rmiBtnM || s == rmiBtnH) {
			checkQuesDegree();
		}
	}
	/**
	 * 检查问题困难度 确认每题的分数
	 */
	private void checkQuesDegree() {
		if (rmiBtnE.isSelected()) {
			pointPerQues = 1;
		}
		else if (rmiBtnM.isSelected()) {
			pointPerQues = 2;
		}
		else if (rmiBtnH.isSelected()) {
			pointPerQues = 3;
		}
		else {
			pointPerQues = 1;
		}
		System.out.println("难度分值：" + pointPerQues);
	}
	/**
	 * 显示问题 及答案 在ui上
	 */
	private void setAnswersBtn(int questionItem) {
		if (questionItem >= 4) {
			showConfirmMesgbox("您的总成绩是:" + getPoint + ",换个姿势重新再来一次?", "问答结束", "img/result.png", 1, "来啊，who care who！", "朕累了退下吧！");
		}
		else {
			String ansWerList = RandomUtil.random(questions.get(questionItem).getOptions().size());
			int a = Integer.parseInt(ansWerList.substring(3));
			int b = Integer.parseInt(ansWerList.substring(2, 3));
			int c = Integer.parseInt(ansWerList.substring(1, 2));
			int d = Integer.parseInt(ansWerList.substring(0, 1));
			lblQuestion.setText(questions.get(questionItem).getQuestionText());
			btnAna.setText(questions.get(questionItem).getOptions().get(a));
			btnAnb.setText(questions.get(questionItem).getOptions().get(b));
			btnAnc.setText(questions.get(questionItem).getOptions().get(c));
			btnAnd.setText(questions.get(questionItem).getOptions().get(d));
		}
	}
	/**
	 * 计分
	 */
	private void checkAnswer(JButton answerBtn) {
		System.out.println("选择的答案：" + answerBtn.getText());
		System.out.println("正确的答案：" + questions.get(initQuestionItem).getAnswer());
		Object oCount = answerCount.get(questions.get(initQuestionItem).getQuestionText());
		System.out.println("是否回答过此问题1：" + oCount);
		if (null == oCount || answerCount.isEmpty()) {
			answerCount.put(questions.get(initQuestionItem).getQuestionText(), answerBtn.getText());
			if (questions.get(initQuestionItem).getAnswer().equals(answerBtn.getText())) {
				getPoint = getPoint + pointPerQues;
				lblScore.setText(String.valueOf(getPoint));
				nextQuestion();
			}
			else {
				showConfirmMesgbox("想要换个姿势再来一次吗?", "回答错误你这个笨蛋！", "img/fail.png", 1, "姿势已换好，com on！", "老子没错！");
			}
		}
		else {
			answerCount.size();
			if (questions.get(initQuestionItem).getAnswer().equals(answerBtn.getText())) {
				getPoint = getPoint + 1;
				lblScore.setText(String.valueOf(getPoint));
				nextQuestion();
			}
			else {
				nextQuestion();
			}
		}
		System.out.println("问题序号：" + initQuestionItem);
	}
	/*------------------------*/
	/**
	 * 下一题
	 */
	private void nextQuestion() {
		initQuestionItem = initQuestionItem + 1;
		setAnswersBtn(initQuestionItem);
	}
	/*------------------------*/
	/**
	 * 信息交互界面
	 */
	private void showMesgbox(String message) {
		JOptionPane.showMessageDialog(frame, message);
	}
	private void showConfirmMesgbox(String message, String title, String imgPath, int operation, String operation1, String operation2) {
		// 提供选项 是否要再回答一次 0 代表选择了 二次回答
		//		String operation1 = "姿势已换好，com on！";
		//		// 1 代表选择了 拒绝回答第二次
		//		String operation2 = "老子没错！";
		//		String operation3 = "退下吧朕累了！";
		Object[] possibilities = {operation1, operation2};
		// 成功
		// n 选择结果 0 代表operation1
		Icon icon = setConfirmMsgBoxIcon(imgPath);
		int n = JOptionPane.showOptionDialog(frame, message, title, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, icon, possibilities, possibilities[operation]);
		System.out.println(n);
		if (n != 0 && n != 1) {
			n = 1;
		}
		System.out.println("他竟然选择了：" + possibilities[n]);
		System.out.println("问题序号：" + possibilities[n]);
		//如果最后一题还没有回答完成（包含第二次机会）
		if (initQuestionItem < 4) {
			if (n == 1) {
				nextQuestion();
			}
		}
		//如果最后一题已经回答完成
		else {
			// 选择退出
			if (n == 1) {
				System.exit(0);
			}
			// 选择再来一次
			else {
				initQuestionItem = 0;
				getPoint = 0;
				answerCount.clear();
				setAnswersBtn(initQuestionItem);
			}
		}
	}
	private Icon setConfirmMsgBoxIcon(String imgPath) {
		String imgFilePath = "file:///" + (currentRootPath + imgPath).substring(1);
		URL imgFileUrl = null;
		try {
			imgFileUrl = new URL(imgFilePath);
			return new ImageIcon(imgFileUrl);
		}
		catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		}
	}
	/*------------------------*/
}
